package com.shujuwuliankeji.ems.cloud.common.security.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.shujuwuliankeji.ems.cloud.common.core.exception.GlobalException;
import com.shujuwuliankeji.ems.cloud.common.core.web.domain.BaseEntity;
import com.shujuwuliankeji.ems.cloud.common.core.web.domain.TreeEntity;
import com.shujuwuliankeji.ems.cloud.common.security.annotation.SaaS;
import com.shujuwuliankeji.ems.cloud.common.security.utils.SecurityUtils;
import com.shujuwuliankeji.ems.cloud.system.api.model.LoginUser;

import cn.hutool.core.bean.BeanUtil;

/**
 * 
 * @author Fanzhongjie
 * @date 2023年1月7日 上午9:10:42
 * @tips SAAS注解
 */
@Aspect
@Component
public class SaaSAspect {

	public SaaSAspect() {
	}

	/**
	 * 定义AOP签名 (切入所有使用SaaS注解的方法)
	 */
	public static final String POINTCUT_SIGN = "@annotation(com.shujuwuliankeji.ems.cloud.common.security.annotation.SaaS)";

	/**
	 * 声明AOP签名
	 */
	@Pointcut(POINTCUT_SIGN)
	public void pointcut() {
	}

	/**
	 * 初始化saas字段值
	 * 
	 * @param joinPoint
	 */
	@Before("pointcut()")
	public void initSaas(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		SaaS saas = signature.getMethod().getAnnotation(SaaS.class);
		String[] tenantFields = saas.value();
		Object[] args = joinPoint.getArgs();
		if (tenantFields != null && tenantFields.length > 0 && args != null && args.length > 0) {
			for (Object arg : args) {
				if (arg instanceof BaseEntity) {
					BaseEntity be = (BaseEntity) arg;
					LoginUser loginUser = SecurityUtils.getLoginUser();
					for (String tenantField : tenantFields) {
						Object property = BeanUtil.getProperty(loginUser, tenantField);
						if (property != null) {
							BeanUtil.setProperty(be, tenantField, property);
						}
					}
				} else if (arg instanceof TreeEntity) {
					TreeEntity be = (TreeEntity) arg;
					LoginUser loginUser = SecurityUtils.getLoginUser();
					for (String tenantField : tenantFields) {
						Object property = BeanUtil.getProperty(loginUser, tenantField);
						if (property != null) {
							BeanUtil.setProperty(be, tenantField, property);
						}
					}
				}
			}
		} else {
			throw new GlobalException("SaaS配置有误，请检查角色配置。");
		}

	}
}
